﻿using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Util
{
    public class AppSettingHelper
    {
        static IConfiguration Configuration { get; set; }
        static string ContentPath { get; set; }

        public AppSettingHelper()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "/appsettings.json";
            Configuration = new ConfigurationBuilder().SetBasePath(ContentPath).Add(new JsonConfigurationSource
            {
                Path = path,
                Optional = false,
                ReloadOnChange = true
            }).Build();
        }
        public AppSettingHelper(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// 获取指定属性值
        /// </summary>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static string app(params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    if (Configuration != null)
                    {
                        return Configuration[string.Join(":", sections)];
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return "";
        }

        /// <summary>
        /// 获取指定对象值
        /// </summary>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static List<T> app<T>(params string[] sections)
        {
            List<T> list = new List<T>();
            Configuration.Bind(string.Join(":", sections), list);
            return list;
        }
        public static T GetSetting<T>(string section)
        {
            try
            {
                return Configuration.GetSection(section).Get<T>();
            }
            catch (Exception ex)
            {
                // Handle exception or log it
                return default(T);
            }
        }
        public static List<string> GetAudience()
        {
            var audienceSection = Configuration.GetSection("AppSettings:JwtSetting:Audience");
            return audienceSection.GetChildren().Select(c => c.Value).ToList();
        }
    }
}
